class User < ActiveRecord::Base
  extend Enumerize

  enumerize :role, in: [:admin, :staff, :editor, :normal_user], default: :normal_user,
                   predicates: true, i18n_scope: 'role'

  class << self
    def find_or_create_from_auth_params auth_params
      user = User.find_or_create_by(id: auth_params[:uid])
      user.update(email: auth_params[:info][:email], username: auth_params[:info][:username],
                                     avatar: auth_params[:info][:avatar][:thumb][:url],
                                     token: auth_params[:credentials][:token],
                                     refresh_token: auth_params[:credentials][:refresh_token],
                                     expires_at: Time.at(auth_params[:credentials][:expires_at]).to_time,
                                     user_info: auth_params[:info])
      user
    end
  end

  def refresh_remember_token
    update(remember_token: SecureRandom.urlsafe_base64, remember_token_created_at: Time.now)
  end

  def is_admin_in_geekpark?
    res = Faraday.get "http://www.geekpark.net/api/v1/user/is_admin.json" do |req|
      req.headers['Authorization'] = "Bearer #{token}"
    end
    JSON.parse(res.body)['is_admin'] 
  end
end
